package src;

import javax.swing.*;
import java.awt.*;
import java.awt.Window;
import java.sql.*;

public class WaterTypeAddDialog extends AddDialog {
    public WaterTypeAddDialog(Window parent, Connection connection) {
        super(parent, "添加用水类型", connection);
        
        // 自动生成类型ID
        String nextTypeId = generateNextTypeId();
        JTextField typeIdField = new JTextField(nextTypeId);
        typeIdField.setEditable(false);
        addInputField("ID:", typeIdField);
        
        addInputField("类型名称:", new JTextField());
        addInputField("单价:", new JTextField());

        confirmButton.addActionListener(e -> {
            try {
                String sql = "INSERT INTO water_type (water_type_id, type_name, unit_price) VALUES (?, ?, ?)";
                PreparedStatement pstmt = connection.prepareStatement(sql);
                pstmt.setString(1, typeIdField.getText());
                pstmt.setString(2, textFields.get("类型名称:").getText());
                pstmt.setDouble(3, Double.parseDouble(textFields.get("单价:").getText()));
                
                pstmt.executeUpdate();
                JOptionPane.showMessageDialog(this, "用水类型添加成功！");
                dispose();
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(this, "添加用水类型失败: " + ex.getMessage());
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "单价必须是数字！");
            }
        });
    }

    private String generateNextTypeId() {
        try {
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT water_type_id FROM water_type ORDER BY water_type_id");
            
            if (!rs.next()) {
                return "WT001";
            }
            
            java.util.Set<Integer> usedIds = new java.util.HashSet<>();
            do {
                String currentId = rs.getString("water_type_id");
                int num = Integer.parseInt(currentId.substring(2));
                usedIds.add(num);
            } while (rs.next());
            
            int nextNum = 1;
            while (usedIds.contains(nextNum)) {
                nextNum++;
            }
            
            return String.format("WT%03d", nextNum);
            
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "生成类型ID失败: " + e.getMessage());
            return "WT001";
        }
    }
} 